# coding: UTF-8

import config
import json

# nodeIp <-> nodeId
node_map = {}
node_count = 0

# linkName <-> linkId
link_map = {}
link_count = 0

done_flag = False
resource_location = config.global_local_unit_test_topo

def set_resource_location(location) :
    global resource_location, done_flag
    resource_location = location
    done_flag = False

def init_node_link_info():
    node_file = open(resource_location + 'node.json')
    try :
        node_text = node_file.read()
    finally :
        node_file.close()

    link_file = open(resource_location + 'link.json')
    try :
        link_text = link_file.read()
    finally :
        link_file.close()

    global node_count
    node_count = 0

    node_json = json.loads(node_text)
    node_list = node_json['topoNodes']

    for node_unit in node_list :
        id = node_unit['id']
        ip = node_unit['loopbackIP']
        node_map[ip] = id
        node_count = node_count + 1

    global link_count
    link_count = 0

    link_json = json.loads(link_text)
    link_list = link_json['topoLinks']

    for link_unit in link_list :
        id = link_unit['id']
        name = link_unit['name']
        link_map[name] = id
        link_count = link_count + 1

    global done_flag
    done_flag = True

def get_node_by_ip(ip) :
    if not done_flag :
        init_node_link_info()

    return node_map[ip]

def get_link_by_name(name):
    if not done_flag :
        init_node_link_info()

    return link_map[name]

def get_node_count() :
    if not done_flag :
        init_node_link_info()

    return node_count

def get_link_count() :
    if not done_flag :
        init_node_link_info()

    return link_count